<template>
    <div class="externalBox">
        <div class="header marginTop10 marginBottom10">
            <span><redStar/> 已选订单</span>
            <el-button icon="edit" size="small" style="float: right;" v-if="refResh" @click="choicePackingList">选择订单</el-button>
        </div>
        <el-row>
            <el-col :span="24">
                <el-table :data="param.packingInfo" border  style="width: 100%;">
                    <el-table-column prop="orderNo" label="订单号" align="center"></el-table-column>
                    <el-table-column label="预计提箱日期" align="center">
                        <template #default="scope"> {{ formatDate(scope.row.planPickupDate, 2) }}</template>
                    </el-table-column>
                    <el-table-column label="下单日期" align="center">
                        <template #default="scope"> {{ formatDate(scope.row.createTime, 2) }} </template>
                    </el-table-column>
                    <el-table-column v-if="refResh" prop="packingAllocationQuantity" label="已开箱量" align="center"> </el-table-column>
                    <el-table-column v-if="refResh" prop="boxQuantity" label="未开箱量" align="center">
                        <template #default="scope">{{scope.row.boxQuantity - scope.row.packingAllocationQuantity}}</template>
                    </el-table-column>
                    <el-table-column v-if="param.packingInfo.length  > 1 && refResh" prop="needPackingNum" label="需开箱量" align="center"> 
                        <template #default="scope">{{scope.row.boxQuantity - scope.row.packingAllocationQuantity}}</template>
                    </el-table-column>
                    <el-table-column v-else-if="refResh" label="需开箱量" align="center">
                        <!-- <template #default="scope"> -->
                            <el-input v-model="needNum" type="number"  :min="1" style="width: 100%;" @change="handleSelectionChange"/>
                        <!-- </template> -->
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
        <el-row class="marginTop20">
            <el-col :span="24">箱型/箱量/箱况</el-col>
            <el-col :span="24">
                <el-table :data="param.boxTypeInfo" border  style="width: 100%;margin-top: 10px;">
                    <el-table-column label="箱型" align="center">
                        <template #default="scope">{{formatBoxType(scope.row.boxType)}}</template>
                    </el-table-column>
                    <el-table-column label="箱况" align="center">
                        <template #default="scope">{{formatBoxCondition(scope.row.boxCondition)}}</template>
                    </el-table-column>
                    <el-table-column prop="boxQuantity" v-if="refResh" label="箱量" align="center"> 
                        <template #default="scope">{{totalIssueBoxNum}}</template>
                    </el-table-column>
                    <el-table-column prop="boxQuantity" v-else label="箱量" align="center"> 
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
        <el-row class="marginTop10 text-right">
            <el-col :span="6"><redStar/>成本价:</el-col>
            <el-col :offset="1" :span="6">
                <div class="input-sel" style="display: flex;">
                  <el-select v-model="param.rentInCurrency" style="width: 60px" placeholder="请选择">
                          <el-option
                              v-for="item in feeCurrencyList"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                          />
                        </el-select>
                  <el-input :formatter="formatterNumberKo" :parser="formatterNumberKo" v-model="param.rentInPrice" style="width: 130px" placeholder="请输入成本价" maxlength="20" />
                </div>
            </el-col>
        </el-row>
        <el-row class="marginTop10 text-right"> 
            <el-col :span="5"><redStar />提箱单有效期范围:</el-col>
            <el-col :offset="1" :span="12">
                <el-date-picker v-model="param.packingValidityPeriod" type="daterange" range-separator="~"
            start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
            </el-col>
        </el-row>
        <el-row class="marginTop10 text-right">
            <el-col :span="5"><redStar/>集装箱公司名称：</el-col>
            <el-col :offset="1" :span="12">
                <el-input v-model="param.boxEast" :disabled ="!refResh" placeholder="请输入"></el-input>
            </el-col>
        </el-row>
        <el-row class="marginTop10 text-right">
            <el-col :span="5"><redStar/>堆场名称：</el-col>
            <el-col :offset="1" :span="12">
                <el-input v-model="param.yardName" :disabled ="!refResh" placeholder="请输入"></el-input>
            </el-col>
        </el-row>
        <el-row class="marginTop10">
            <el-col :span="5" class="text-right">放箱单：</el-col>
            <el-col :offset="1" :span="15"><img-upload ref="packingRef1" :fileList="fileList1" :type="'pdf_jpg_png_zip'"/></el-col>
        </el-row>
        <el-row class="marginTop10">
            <el-col :span="5" class="text-right">附件：</el-col>
            <el-col :offset="1" :span="15"><img-upload ref="packingRef2" :fileList="fileList2" :limit="10" :type="'pdf_jpg_png_zip'" :multiple="true"/></el-col>
        </el-row>
        <el-row class="marginTop10">
            <el-col :span="5" class="text-right">备注：</el-col>
            <el-col :offset="1" :span="15">
                <el-input v-model="param.remark" type="textarea" placeholder="请输入内容" />
            </el-col>
        </el-row>
        <div class="text-center marginTop20">
            <el-button type="primary" v-if="refResh" @click="handleSubmit">提交</el-button>
            <el-button type="primary" v-else @click="drawerPackingOpen">提交</el-button>
        </div>
    </div>
    <el-dialog v-model="param.dialogPacking" title="租箱订单选择" width="1300">
        <AllPacking :subassemblyInfo="subassemblyInfo" @checkOrderList="checkOrderList" :orderType="props.orderType" :currentNumber="param.currentNumber" :sources="10" :disable="true"/>
    </el-dialog>
</template>
<script lang="ts" setup>
import {ref, reactive, onMounted, computed, inject} from 'vue'
import redStar from '@/views/components/redStar.vue';
import { formatDate, formatBoxType, formatBoxCondition ,formatterNumberKo} from '@/utils'
import AllPacking from '@/views/orderManage/huiDiaoOrder/component/allPacking.vue';
import imgUpload from '@/components/upload/index.vue'
import { addPacking ,getPackingData,getExpiredReopen} from '@/api/orderManage/packing'
import { ElMessage } from 'element-plus'

const config = inject('config');
const emit = defineEmits(['closeDialog'])
const needNum = ref(0)
const props = defineProps({
  packingInfo: {
    type: Object,
    default: () => {}
  },
  orderType:{
    type: Number,
    default: 0  // 5 - 租箱， 10 - 回调 ，（200 - 售箱）
  },
  sources:{
    type:String,
    default: ''
  }
})
const feeCurrencyList=ref([
  {
    value:'CNY',
    label:'¥'
  },
  {
    value:'USD',
    label:'$'
  },
])
onMounted(() => {
    param.currentNumber = props.packingInfo[0]?.orderNo
    if(config.sources == "internal"){ 
        param.boxTypeInfo = []
        needNum.value = param.packingInfo[0]?.boxQuantity - param.packingInfo[0]?.packingAllocationQuantity
        param.packingInfo.forEach((item: any,index: number) => {
            let info = {
                "boxType":item.boxType,
                "boxCondition":item.boxCondition,
                "boxQuantity":item.boxQuantity
            }
            param.boxTypeInfo.push(info)
        })
    }
})

const param = reactive({
    oldPackingId:'',
    dialogPacking:false, //选择订单弹窗
    packingInfo: props.packingInfo,
    boxTypeInfo:[], //箱型/箱况/箱量
    stagingData: props.packingInfo, // 暂存数据
    packingValidityPeriod:"",
    boxEast:"",
    yardName:"",
    remark:"",
    boxType: props.packingInfo[0]?.boxType,
    boxCondition: props.packingInfo[0]?.boxCondition,
    currentNumber: "", //订单内开提箱单 当前单号
    rentInCurrency:'CNY',
    rentInPrice:0,

})
const subassemblyInfo = reactive({
    orderType: props.orderType, //  5 - 租箱， 10 - 回调 ，（200 - 售箱）
    agentName: "",
    boxType:param.stagingData.boxType,
    boxCondition:param.stagingData.boxCondition,
    orderNo:props.packingInfo.orderNo,
    info: {}
})
//查询所有可开提箱单的订单（针对当前角色）
const choicePackingList = () => {
    param.dialogPacking = true
}

//详情接口
const fileList1=ref([]) //附件默认
const fileList2=ref([]) //附件默认
const showInfo = (row: any) => {
  if (!row.id) {
    return ElMessage({ message: '暂无提箱单id信息', type: 'error' })
  }
  getPackingData(row.id).then((res: any) => {
    const data = res.data
    let packingValidityPeriodList=[]
    if(data.packingValidityPeriodStart){
        packingValidityPeriodList.push(data.packingValidityPeriodStart)
        packingValidityPeriodList.push(data.packingValidityPeriodEnd)
    }
    param.packingValidityPeriod=packingValidityPeriodList
    param.packingInfo=JSON.parse(data.orderList)
    needNum.value = param.packingInfo[0]?.boxQuantity - param.packingInfo[0]?.packingAllocationQuantity
    param.boxTypeInfo = []
    let boxInfo = {
        boxType:data.boxType,
        boxCondition:data.boxCondition,
        boxQuantity:data.totalQuantity-data.packedQuantity
    }
    param.boxEast=data.outBoxCompanyName
    param.boxTypeInfo.push(boxInfo) 
    // param.instruction=data.instruction
    param.selectedContainerList = JSON.parse(data.containerNoList)
    fileList1.value=JSON.parse(data.pdfFile)
    fileList2.value=JSON.parse(data.packingFileList)

    param.oldPackingId=data.id
    param.yardName=data.yardName
    // param.boxEastYardId=data.yardId
    param.remark=data.remark
  })
};
//重开提交
const drawerPackingOpen = () => {
    let pdfFile = packingRef1.value.resultList || []
    let packingFileList = packingRef2.value.resultList || []
    let data = {
    oldPackingId: param.oldPackingId,
        packingValidityPeriodStart: param.packingValidityPeriod[0],
        packingValidityPeriodEnd: param.packingValidityPeriod[1],
        // instruction:param.instruction,
        // boxEastYardId: param.boxEastYardId,
        // yardContactSerialNo: param.yardContactSerialNo,
        pdfFile:JSON.stringify(pdfFile), // 附件

        packingFileList:JSON.stringify(packingFileList), // 附件
        remark: param.remark,
    }

    getExpiredReopen(data).then(res => {
        if (res.code == "00000") {
            ElMessage.success("提交成功")
            refResh.value=true
            emit('closeDialog')
        }else{
            ElMessage.error(res.msg)
        }
    }).catch(err => {
        console.log("ERROR:",err)
    })
}
const refResh=ref(true) //判断是否是重开
const openBox = (info) => {
    refResh.value=false
    showInfo(info)
}
//选中的可开提箱单的订
const checkOrderList = (list: any) => {
    console.log(list,param.stagingData)
    param.dialogPacking = false
    if(list.length == 0) return param.packingInfo = param.packingInfo.filter(item => item.orderNo == param.currentNumber) // 未选中订单 不进行后续操作
    param.packingInfo = param.stagingData.concat(list)
    param.packingInfo = Array.from(new Map(param.packingInfo.map(item => [item.orderNo, item])).values());
    
    param.boxTypeInfo = []
    param.packingInfo.forEach((item: any,index: number) => {
        if(index == 0){
            let info = {
                "boxType":item.boxType,
                "boxCondition":item.boxCondition,
                "boxQuantity":item.boxQuantity
            }
            item.needPackingNum = 1
            param.boxTypeInfo.push(info)
            param.boxType = item.boxType
            param.boxCondition = item.boxCondition
        }
        
    })

    needNum.value = param.packingInfo[0]?.boxQuantity - param.packingInfo[0]?.packingAllocationQuantity
}


const packingRef1 = ref([])
const packingRef2 = ref([])

const handleSubmit = () => {
    let orderListInfo = []
    if(param.packingInfo.length == 1){
        param.packingInfo.forEach((item: any) => {
            let info = { 
                "orderId": item.id, 
                "orderNo": item.orderNo, 
                "planPickupDate": item.planPickupDate, 
                "createTime": item.createTime, 
                "boxQuantity": item.boxQuantity, 
                // "needPackQuantity": item.needPackingNum 
                "needPackQuantity":needNum.value
            }
            orderListInfo.push(info)
        })
    }else{
        param.packingInfo.forEach((item: any) => {
            let needPackQuantity = item.boxQuantity - item.packingAllocationQuantity
            let info = { 
                "orderId": item.id, 
                "orderNo": item.orderNo, 
                "planPickupDate": item.planPickupDate, 
                "createTime": item.createTime, 
                "boxQuantity": item.boxQuantity, 
                "needPackQuantity": needPackQuantity 
            }
            orderListInfo.push(info)
        })
    }
    
    const pdfFile = packingRef1.value.resultList || []
    const packingFileList = packingRef2.value.resultList || []
    let requestInfo = {
        orderType: props.orderType,
        containerNo: null,
        orderList: JSON.stringify(orderListInfo),
        packingValidityPeriodStart: param.packingValidityPeriod[0],
        packingValidityPeriodEnd: param.packingValidityPeriod[1],
        remark: param.remark,
        pdfFile:JSON.stringify(pdfFile),// 提箱单附件
        packingFileList:JSON.stringify(packingFileList), // 附件
        boxType: param.boxType,
        boxCondition: param.boxCondition,
        outBoxCompanyName: param.boxEast?.trim(),//外调集装箱公司名称 
        yardName: param.yardName?.trim(),//堆场名称
        containerClassify: 15,  // 5:自有箱  15：外调箱 
        rentInPrice:param.rentInPrice,
        rentInCurrency:param.rentInCurrency,
    }
    
    addPacking(requestInfo).then(res => {
        if (res.code == "00000") {
            ElMessage.success("提交成功")
            emit('closeDialog')
            // location.reload()
        }else{
            ElMessage.error(res.msg)
        }
    }).catch(err => {
        console.log("ERROR:",err)
    })
    
}

const handleSelectionChange = (val: any) => {
    // 只有订单选择一个时 需开箱量才可修改时 
    if(val < 1){
        val = 1
    } 
    // param.packingInfo[0].needPackingNum = val
    needNum.value = val
}

const totalIssueBoxNum = computed(() => {
    let total = 0
    let ykTltal = 0
     if(param.packingInfo.length == 1) return needNum.value || "--"  
    param.packingInfo.forEach((item: any) => {
        total += item.boxQuantity
        ykTltal += item.packingAllocationQuantity
    })

    return total - ykTltal
})
defineExpose({
    openBox
})
</script>

<style lang="scss" scoped>

</style>